package com.longcai.cm.moudules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longcai.cm.base.aop.Log;
import com.longcai.cm.base.bean.PageVo;
import com.longcai.cm.base.bean.Pageable;
import com.longcai.cm.bean.R;
import com.longcai.cm.common.utils.RequestUtil;
import com.longcai.cm.common.utils.StringUtils;
import com.longcai.cm.moudules.system.domain.SysUsers;
import com.longcai.cm.moudules.system.domain.SysUsersRole;
import com.longcai.cm.moudules.system.service.SysUserRolesService;
import com.longcai.cm.moudules.system.service.SysUsersService;
import com.longcai.cm.moudules.system.utils.PasswordHelper;
import com.longcai.cm.moudules.system.utils.UUID;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户管理
 *
 * @author chenyue
 * @Description: TODO
 * @file:
 * @throws
 * @date 2018/11/14 15:31
 */
@Controller
@RequestMapping("/sysUsers")
@Api(value = "系统管理-用户", tags = "系统管理-用户")
@ApiSort(4)
public class SysUsersController {


    @Resource
    private SysUsersService sysUsersService;

    @Resource
    private SysUserRolesService userRoleService;

    /**
     * 【API】----【获取列表数据----带分页】
     *
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return R
     */

    @PostMapping("/getList")
    @ResponseBody
    @ApiOperation(value = "【S4002】获取系统用户列表", notes = "获取系统用户列表")
    @ApiOperationSupport(order = 2)
    @Log(value = "获取系统用户列表", type = "1")
    @RequiresPermissions("userList:list")
    public R getListPC(HttpServletRequest request, HttpServletResponse response) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        PageVo<SysUsers> result = sysUsersService.getPageBean(pageInfo, SysUsers.class);
        return R.success(result);
    }

    /**
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return R
     */
    @PostMapping("/getUserInfoById")
    @ResponseBody
    @ApiOperation(value = "【S4003】根据id获取单个用户详情", notes = "获取单个用户详情")
    @ApiOperationSupport(order = 3)
    @Log(value = "查询单个用户信息", type = "1")
    public R getVo(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("userId");

        SysUsers userVo = sysUsersService.getById(id);
        return R.success(userVo);
    }

    /**
     * 【API】---- 根据用户id获取角色ids
     *
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return R
     */
    @PostMapping("/getRolesIdByUid")
    @ResponseBody
    @ApiOperation(value = "【S4004】根据用户id获取角色ids", notes = "根据用户id获取角色ids")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "角色id", name = "id", dataType = "string", required = true),
    })
    public R<List<String>> getRolesIdByUid(HttpServletRequest request, HttpServletResponse response) {
        String userId = request.getParameter("id");
        List<String> roleList = new ArrayList<>();

        QueryWrapper<SysUsersRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<SysUsersRole> userRoleList = userRoleService.list(wrapper);

        for (SysUsersRole sysUsersRole : userRoleList) {
            roleList.add(sysUsersRole.getRoleId());
        }
        return R.success(roleList);
    }


    /**
     * 【API】---- 【保存用户信息】
     *
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return R
     */
    @PostMapping("/save")
    @ResponseBody
    @ApiOperation(value = "【S4006】保存用户信息", notes = "保存用户信息")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户角色id", name = "roles", dataType = "string", required = true),
    })
    @Log(value = "保存用户信息", type = "1")
    public R savePC(SysUsers vo, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        String roleIdString = request.getParameter("roles");

        if (StringUtils.isNotBlank(id)) {
            String encryptPassword = PasswordHelper.encryptPassword(vo.getPassword());
            vo.setPassword(encryptPassword);
            sysUsersService.updateById(vo);
        } else {
            String encryptPassword = PasswordHelper.encryptPassword(vo.getPassword());
            vo.setPassword(encryptPassword);
            vo.setId(UUID.get());
            sysUsersService.save(vo);
        }

        //保存用户角色信息
        if (StringUtils.isNotBlank(roleIdString)) {
            //删除原来的关联关系

            QueryWrapper<SysUsersRole> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", vo.getId());
            userRoleService.remove(wrapper);

            //设置新的关联关系
            String[] roles = roleIdString.split(",");
            for (String string : roles) {
                SysUsersRole aRole = new SysUsersRole(string, vo.getId());
                aRole.setId(UUID.get());
                userRoleService.save(aRole);
            }
        }

        return R.success();
    }


    /**
     * 更新用户密码
     *
     * @param request  [请求信息]
     * @param response [返回信息]
     * @return R
     */
    @PostMapping(value = "/updatePassword")
    @ResponseBody
    @ApiOperation(value = "【S3007】更新系统用户密码", notes = "更新系统用户密码")
    @ApiOperationSupport(order = 7)
    public R updatePassWord(HttpServletRequest request, HttpServletResponse response) {
        String userId = request.getParameter("userId");
        String newPassWord = request.getParameter("newPassWord");
        SysUsers userVo = sysUsersService.getById(userId);
        if (userVo != null) {
            String password = PasswordHelper.encryptPassword(newPassWord);
            userVo.setPassword(password);
            sysUsersService.updateById(userVo);
        }
        return R.success();
    }


    /**
     * 更新用户信息
     *
     * @param request  [请求信息]
     * @param response [返回信息]
     * @return R
     */
    @PostMapping(value = "/updateUserInfo")
    @ResponseBody
    @ApiOperation(value = "【S3007】更新用户信息", notes = "更新用户信息")
    @ApiOperationSupport(order = 7)
    public R updateUserInfo(SysUsers vo, HttpServletRequest request, HttpServletResponse response) {
        SysUsers byId = sysUsersService.getById(vo.getId());
        if (byId != null) {
            sysUsersService.updateById(vo);
        }
        return R.success();
    }


    /**
     * 【API】---- 【删除用户信息】
     *
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return R
     */
    @PostMapping("/delete")
    @ResponseBody
    @ApiOperation(value = "【S3009】批量删除用户信息", notes = "批量删除用户信息")
    @ApiOperationSupport(order = 9)
    @Log(value = "批量删除用户信息", type = "1")
    public R delete(HttpServletRequest request, HttpServletResponse response, Model model) {

        response.setContentType("text/html;charset=utf-8");
        String ids = request.getParameter("ids");
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            //删除用户信息
            sysUsersService.removeById(idString);
        }

        return R.success();
    }


}
